
package com.epam.android.training.level1.activity;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.db.dao.RssDao;
import com.epam.android.training.level1.db.dao.impl.RssDaoImpl;

import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.widget.Toast;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Activity that is responsible for application configuration (RSS feeds,
 * default page to be loaded, etc).
 * 
 * @author Anton Novikau
 */
public class SettingsActivity extends PreferenceActivity implements IntentActions {
  public static final String DEFAULT_PAGE_KEY = "default_page_preference";

  public static final String RSS_REFRESH_INTERVAL_KEY = "rss_refresh_preference";

  public static final String RSS_FEED_PREFERENCE_KEY = "rss_feeds_preference";

  public static final String POLL_ACTIVATE_SYNC_SERVICE_KEY = "activate_poll_sync_preferece";

  public static final String POLL_REFRESH_INTERVAL_KEY = "poll_refresh_preference";

  private static final String TAG = SettingsActivity.class.getSimpleName();

  private RssDao rssDao;

  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    rssDao = new RssDaoImpl(this);

    addPreferencesFromResource(R.xml.settings);
    addSummaryToListPref(DEFAULT_PAGE_KEY);
    addRssSyncAction();
    addFeedSyncIntervalAction();
    addPollSyncIntervalAction();
    addActivateSyncServiceAction();
  }

  private void addSummaryToListPref(String prefKey) {
    ListPreference defaultPagePref = (ListPreference) findPreference(prefKey);
    CharSequence defaultPage = defaultPagePref.getEntry();
    defaultPagePref.setSummary(defaultPage);
    defaultPagePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        ListPreference listPref = (ListPreference) preference;
        listPref.getEntryValues();
        int index = listPref.findIndexOfValue(newValue.toString());
        listPref.setSummary(listPref.getEntries()[index]);
        return true;
      }
    });
  }

  private void addRssSyncAction() {
    EditTextPreference feedPref = (EditTextPreference) findPreference(RSS_FEED_PREFERENCE_KEY);
    feedPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        String feedProp = String.valueOf(newValue);
        try {
          URL feedUrl = new URL(feedProp);
          long feedId = rssDao.createFeed(feedUrl);
          if (feedId > 0) {
            String title = rssDao.getFeedTitle(feedId);
            preference.setSummary(title);
            sendBroadcast(new Intent(ACTION_RENEW_WIDGET));
            return true;
          }

          return false;
        } catch (MalformedURLException e) {
          Log.e(TAG, "Unable to parse feed URL", e);
          Toast.makeText(SettingsActivity.this, getString(R.string.bad_feed_url_message, feedProp),
              Toast.LENGTH_LONG).show();
          return false;
        }
      }
    });
  }

  private void addPollSyncIntervalAction() {
    EditTextPreference pref = (EditTextPreference) findPreference(POLL_REFRESH_INTERVAL_KEY);
    pref.setSummary(getString(R.string.settings_refresh_summary, pref.getText()));
    pref.setOnPreferenceChangeListener(new RefreshIntervalPreferenceChangeListener(
        new SettingsCallback() {

          @Override
          public boolean execute() {
            // restart service with new interval.
            stopService(new Intent(ACTION_SYNC_POLL));
            startService(new Intent(ACTION_SYNC_POLL));
            return true;
          }
        }));
  }

  private void addFeedSyncIntervalAction() {
    EditTextPreference pref = (EditTextPreference) findPreference(RSS_REFRESH_INTERVAL_KEY);
    pref.setSummary(getString(R.string.settings_refresh_summary, pref.getText()));
    pref.setOnPreferenceChangeListener(new RefreshIntervalPreferenceChangeListener(
        new SettingsCallback() {

          @Override
          public boolean execute() {
            return true;
          }
        }));
  }

  private void addActivateSyncServiceAction() {
    final CheckBoxPreference pref = (CheckBoxPreference) findPreference(POLL_ACTIVATE_SYNC_SERVICE_KEY);
    pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (pref.isChecked()) {
          // if old value was true and chanched we stop service.
          stopService(new Intent(ACTION_SYNC_POLL));
        } else {
          // if old value was false and changed we start service.
          startService(new Intent(ACTION_SYNC_POLL));
        }
        return true;
      }
    });
  }

  private class RefreshIntervalPreferenceChangeListener implements
      Preference.OnPreferenceChangeListener {
    private final SettingsCallback callback;

    public RefreshIntervalPreferenceChangeListener(SettingsCallback callback) {
      this.callback = callback;
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
      int refreshInterval = Integer.parseInt(newValue.toString());
      String summary = getString(R.string.settings_refresh_summary, refreshInterval);
      preference.setSummary(summary);

      return callback != null ? callback.execute() : true;
    }
  }

  private interface SettingsCallback {
    boolean execute();
  }
}
